<template>
  <div>
    <el-row class="p-d b-f header">
      <el-page-header @back="goBack" :content="title">
      </el-page-header>
      <span class="saveBtn" v-if="isFlag!=='look'">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button type="primary" plain @click="goBack">取消</el-button>
      </span>
    </el-row>
    <div class="p-d">
      <div class="p-d b-f">
        <el-row class="p-b">
          <h1 class="before">基本信息</h1>
        </el-row>
        <el-form ref="ruleForm" :model="form" :rules="rules" label-width="160px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="申报指南：" prop="guideId">
                <el-select style="width: 100%;" v-model="form.guideId" placeholder="请选择申报指南" :disabled="isFlag=='look'" @change="changeGuild">
                  <el-option v-for="item in treeList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="申报条目：" prop="guideName">
                <el-select style="width: 100%;" v-model="form.guideName" placeholder="请选择申报条目" value-key="name" :disabled="isFlag=='look'"
                  @change="changeItems">
                  <el-option v-for="item in itemsList" :key="item.id" :label="item.name" :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申报领域：" prop="domainName">
                <el-input v-model="form.domainName" placeholder="请选择申报领域" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称：" prop="name">
                <el-input v-model="form.name" placeholder="请输入项目名称" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申报单位：" prop="departmentName">
                <el-input v-model="form.departmentName" placeholder="请输入申报单位" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目负责人：" prop="projectHeader">
                <el-input v-model="form.projectHeader" placeholder="请输入项目负责人" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人：" prop="contacts">
                <el-input v-model="form.contacts" placeholder="请输入联系人" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系电话：" prop="contactsTel">
                <el-input v-model="form.contactsTel" placeholder="请输入联系电话" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申报地址：" prop="contactsAddress">
                <el-input v-model="form.contactsAddress" placeholder="请输入申报地址" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="研究周期：" prop="researchCycle" class="flex-rowform">
                <el-input v-model="form.researchCycle" placeholder="请输入研究周期" type="number" oninput="if(value<0)value=0" :disabled="isFlag=='look'" />
                <span class="r-span">（月）</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究经费：" prop="researchFund" class="flex-rowform">
                <el-input v-model="form.researchFund" placeholder="请输入研究经费" type="number" oninput="if(value<0)value=0" :disabled="isFlag=='look'" />
                <span class="r-span">（万元）</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="研究方向：" prop="researchDirect" class="flex-rowform">
                <el-input v-model="form.researchDirect" type="textarea" rows="7" placeholder="请输入研究方向" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="研究内容：" prop="researchContent" class="flex-rowform">
                <el-input v-model="form.researchContent" type="textarea" rows="7" placeholder="请输入研究内容" :disabled="isFlag=='look'" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-row class="p-t person">
          <h1 class="before">人员信息</h1>
          <div class="r-btn" v-if="isFlag!=='look'">
            <el-upload ref="uploadRefXls" class="upload-demo" action="#" :limit="1" :on-change="handleChangeXls" :auto-upload="false"
              :show-file-list="false" :on-exceed="handleExceedXls" accept=".xls,.xlsx">
              <template #trigger>
                <el-button type="primary" size="small">批量导入</el-button>
              </template>
            </el-upload>
            <el-button type="primary" size="small" @click="download()">下载模板</el-button>
          </div>
        </el-row>
        <el-row class="p-t">
          <TableCompEle class="m-t" ref="multipleTable" :tableData="tableData" :tableConfig="tableConfig"
            :tableAction="isFlag!=='look'?tableAction:null" :isSelect="false" :isIndex="true" :isShowPage="false">
          </TableCompEle>
          <div class="flex-c" v-if="isFlag!=='look'">
            <el-button @click="addUser">
              <i class="el-icon-plus" />
              新增成员
            </el-button>
          </div>
        </el-row>
        <el-row class="p-t">
          <h1 class="before">支撑材料</h1>
        </el-row>
        <el-row class="p-t">
          <TableCompEle class="m-t" ref="multipleTableFile" :tableData="tableDataFile" :tableConfig="tableConfigFile" :tableAction="tableActionFile"
            :isSelect="false" :isIndex="true" :isShowPage="false">
            <template v-slot:upload="scope" v-if="isFlag!=='look'">
              <span>
                <el-upload ref="uploadRef" class="upload-demo" action="#" :limit="1"
                  :on-change="(file, fileList) => {handleChange(file, fileList, scope.row)}" :auto-upload="false" :show-file-list="false"
                  :on-exceed=" ( fileList) => {handleExceed(fileList, scope.row)}">
                  <template #trigger>
                    <el-link :underline="false" type="primary">上传</el-link>
                  </template>
                </el-upload>
              </span>
            </template>
          </TableCompEle>
          <div class="flex-c" v-if="isFlag!=='look'">
            <el-button @click="addFile">
              <i class="el-icon-plus" />
              新增材料
            </el-button>
          </div>
        </el-row>
        <div v-if="isResult&&formRes">
          <el-row class="p-t">
            <h1 class="before">评审结果</h1>
          </el-row>
          <el-form ref="ruleForm" :model="formRes" label-width="160px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="平均分：" prop="avgScore">
                  <el-input v-model="formRes.avgScore" placeholder="请输入平均分" :disabled="isFlag=='look'" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="回避数：" prop="avoidCount">
                  <el-input v-model="formRes.avoidCount" placeholder="请输入回避数" :disabled="isFlag=='look'" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="评审结论：" prop="reviewResultContent">
                  <el-input v-model="formRes.reviewResultContent" type="textarea" rows="7" placeholder="请输入评审结论" :disabled="isFlag=='look'" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="评审意见：" prop="reviewOpinion">
                  <el-input v-model="formRes.reviewOpinion" type="textarea" rows="7" placeholder="请输入评审意见" :disabled="isFlag=='look'" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-form-item label="专家组：" prop="name4">
              </el-form-item>
              <TableCompEle class="m-t" ref="multipleTable" :tableData="formRes.techTalentsList?formRes.techTalentsList:[]"
                :tableConfig="tableConfigUser" rowKey="userId" :isSelect="false" :isIndex="true"></TableCompEle>
            </el-row>
          </el-form>
        </div>
      </div>
    </div>
    <PreviewPdf v-if="showPdf" :pdfUrl="pdfUrl" @closeLookPdf="closeLookPdf" />
  </div>
</template>

<script>
import { uploadFile, deleteFile, getWord2Pdf } from '@/api/common.js'
import { getTreeList } from '@/api/guide.js'
import {
  downloadTemplate,
  uploadAndExtractItem,
  addProject,
  updateProject,
  getDetail,
  getResultDetail
} from '@/api/projectDeclare.js'
import PreviewPdf from '@/views/common/previewPdf.vue'
export default {
  components: { PreviewPdf },
  computed: {
    isFlag() {
      return this.$route.params.flag
    },
    rowId() {
      return this.$route.params.id
    },
    isResult() {
      return this.$route.params.isResult
    }
  },
  data() {
    return {
      showPdf: false,
      pdfUrl: null,
      title: '',
      accept: '.doc,.docx,.pdf',
      treeList: [],
      itemsList: [],
      form: {
        guideId: null,
        guideItemId: null,
        domainName: '',
        guideName: '',
        name: '',
        departmentName: '',
        projectHeader: '',
        contacts: '',
        contactsTel: '',
        contactsAddress: '',
        researchCycle: 0,
        researchFund: 0,
        researchDirect: ''
      },
      rules: {
        guideId: [
          { required: true, message: '指南不能为空！', trigger: 'blur' }
        ],
        guideItemId: [
          { required: true, message: '指南条目不能为空！', trigger: 'blur' }
        ],
        domainName: [
          { required: true, message: '申报领域不能为空！', trigger: 'blur' }
        ],
        guideName: [
          { required: true, message: '申报条目不能为空！', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '项目名称不能为空！', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '单位不能为空！', trigger: 'blur' }
        ],
        projectHeader: [
          { required: true, message: '项目负责人不能为空！', trigger: 'blur' }
        ],
        contacts: [
          { required: true, message: '联系人不能为空！', trigger: 'blur' }
        ],
        contactsTel: [
          { required: true, message: '联系电话不能为空！', trigger: 'blur' }
        ]
      },
      tableData: [],
      tableConfig: [
        {
          isEdit: true,
          isType: 'Input',
          prop: 'name',
          placeholder: '请输入',
          label: '姓名'
        },
        {
          isEdit: true,
          isType: 'Select',
          prop: 'gender',
          label: '性别',
          placeholder: '请选择',
          options: [
            {
              label: '男',
              value: '男'
            },
            {
              label: '女',
              value: '女'
            }
          ]
        },
        {
          isEdit: true,
          isType: 'Input',
          prop: 'idCard',
          placeholder: '请输入',
          label: '身份证号码'
        },
        {
          isEdit: true,
          isType: 'Input',
          prop: 'title',
          placeholder: '请输入',
          label: '职称'
        },
        {
          isEdit: true,
          isType: 'Input',
          prop: 'major',
          placeholder: '请输入',
          label: '专业'
        },
        {
          isEdit: true,
          isType: 'Input',
          prop: 'taskWork',
          placeholder: '请输入',
          label: '任务分工'
        },
        {
          isEdit: true,
          isType: 'Input',
          prop: 'workUnit',
          placeholder: '请输入',
          label: '工作单位'
        }
      ],
      tableAction: {
        align: () => 'center',
        width: () => String(120),
        operations: [
          {
            label: '修改',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return !row.isHandle
            },
            method: row => {
              this.$set(row, 'isHandle', true)
            }
          },
          {
            label: '删除',
            isLink: true,
            type: 'danger',
            isShow: row => {
              return !row.isHandle
            },
            method: row => {
              this.deleteFun(row)
            }
          },
          {
            label: '保存',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return row.isHandle
            },
            method: row => {
              this.$set(row, 'isHandle', false)
            }
          },
          {
            label: '取消',
            isLink: true,
            type: 'primary',
            isShow: row => {
              return row.isHandle
            },
            method: row => {
              this.$set(row, 'isHandle', false)
            }
          }
        ]
      },
      tableDataFile: [],
      tableConfigFile: [
        {
          isEdit: true,
          isType: 'Input',
          prop: 'name',
          placeholder: '请输入',
          label: '材料名称'
        },
        {
          isLink: true,
          prop: 'fileName',
          type: 'primary',
          label: '文件名称',
          method: row => {
            console.log('[ row ] >', row)
            this.downloadLink(row)
          }
        }
      ],
      tableActionFile: {
        align: () => 'center',
        width: () => String(120),
        operations: [
          {
            label: '上传',
            prop: 'upload',
            isSlot: true
          },
          {
            label: '删除',
            isLink: true,
            type: 'danger',
            isShow: () => {
              return this.isFlag !== 'look'
            },
            method: row => {
              this.delFile(row)
            }
          },
          {
            label: '预览',
            isLink: true,
            type: 'primary',
            isShow: () => {
              return this.isFlag === 'look'
            },
            method: row => {
              this.lookLink(row)
            }
          },
          {
            label: '下载',
            isLink: true,
            type: 'primary',
            isShow: () => {
              return this.isFlag === 'look'
            },
            method: row => {
              this.downloadLink(row)
            }
          }
        ]
      },
      formRes: {},
      tableConfigUser: [
        {
          prop: 'talentsName',
          label: '专家姓名'
        },
        {
          prop: 'groupTitle',
          label: '职责'
        },
        {
          prop: 'jobTitle',
          label: '技术职称'
        },
        {
          prop: 'careerDirection',
          label: '职业方向'
        },
        {
          prop: 'reviewOpinion',
          label: '专家意见'
        },
        {
          isLink: true,
          prop: 'fileName',
          type: 'primary',
          label: '文件',
          method: row => {
            this.downloadLink(row)
          }
        }
      ]
    }
  },
  watch: {
    'form.guideId'(val) {
      this.itemsList = this.treeList.filter(item => {
        return item.id == val
      })[0].items
    }
  },
  created() {
    this.initTree()
    switch (this.isFlag) {
      case 'add':
        this.title = '新增'
        break
      case 'edit':
        this.title = '修改'
        this.getDetail()
        break
      case 'look':
        this.title = '详情'
        this.getDetail()
        break
    }
    if (this.isResult) {
      getResultDetail({ projectId: this.rowId }).then(res => {
        if (res.code == 200 && res.data) {
          this.formRes = res.data
        }
      })
    }
  },
  mounted() { },
  methods: {
    downloadLink(item) {
      this.downloadByUrl(item.fileName, item.filePath)
    },
    lookLink(item) {
      let txt = this.getMatchType(item.filePath)
      if (txt === 'word') {
        getWord2Pdf({ wordPath: item.filePath }).then(res => {
          if (res.data) {
            this.lookPdf(res.data)
          } else {
            this.$message.warning('暂无法预览，请下载后查看！')
          }
        })
      } else {
        if (txt === 'pdf') {
          this.lookPdf(item.filePath)
        } else {
          this.$message.warning('文件不支持预览！')
        }
      }
    },
    lookPdf(url) {
      this.pdfUrl = url
      this.showPdf = true
    },
    closeLookPdf() {
      this.showPdf = false
      this.pdfUrl = null
    },
    initTree() {
      getTreeList().then(res => {
        this.treeList = res.data
      })
    },
    changeGuild(val) {
      this.form.guideItemId = val
      this.itemsList = this.treeList.filter(item => {
        return item.id == val
      })[0].items
    },
    changeItems(val) {
      this.form.guideItemId = val.id
      this.form.guideName = val.name
      this.form.domainName = val.domainName
    },
    addUser() {
      this.tableData.push({
        name: '',
        gender: '',
        idCard: '',
        title: '',
        major: '',
        taskWork: '',
        workUnit: '',
        isHandle: true
      })
    },
    del(row) {
      let itemIndex = this.tableData.findIndex(function (obj) {
        return row === obj
      })
      this.tableData.splice(itemIndex, 1)
    },
    addFile() {
      this.tableDataFile.push({
        name: '',
        fileName: '',
        fileOriginPath: '',
        filePath: '',
        isHandle: true
      })
    },
    getDetail() {
      getDetail({ id: this.rowId }).then(res => {
        this.form = res.data.techResearchProject
        let arr = res?.data?.techResearchProjectMembers ?? []
        this.tableData = arr
        this.tableDataFile = res.data.techResearchProjectSupportFiles
      })
    },
    goBack() {
      this.$router.go(-1)
    },
    show(obj) {
      this.dialogVisible = true
      this.title = obj.title
      console.log('[ obj ] >', obj)
    },
    submitForm() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          let params = {
            techResearchProject: this.form,
            techResearchProjectMembers: this.tableData,
            techResearchProjectSupportFiles: this.tableDataFile
          }
          if (this.isFlag == 'add') {
            addProject(params).then(() => {
              this.goBack()
            })
          } else {
            updateProject(params).then(() => {
              this.goBack()
            })
          }
        } else {
          return false
        }
      })
    },
    cancel() {
      this.form = this.$options.data().form
      this.$refs.ruleForm.clearValidate()
      this.dialogVisible = false
      this.tableData = []
      this.tableDataFile = []
      this.$emit('close')
    },
    // 下载模板
    download() {
      downloadTemplate()
    },
    // xls
    handleChangeXls(file) {
      // uploadAndExtractItem
      const _file = file?.raw ?? file
      const formData = new FormData()
      formData.append('file', _file)
      formData.append('pathType', file.name.split('.').pop())
      uploadAndExtractItem(formData).then(res => {
        this.tableData = res.data
      })
    },
    // 多次上传覆盖
    handleExceedXls(file) {
      this.$refs.uploadRefXls.clearFiles()
      this.handleChangeXls(file[0])
    },
    // 支持材料
    // handleChange(file, fileList, row) {
    //   console.log('[ file, row ] >', file, fileList, row)
    //   row = Object.assign(row, file)
    //   console.log('[ this.tableDataFile ] >', this.tableDataFile)
    // },
    // // 多次上传覆盖
    // handleExceed(file) {
    //   this.$refs.uploadRef.clearFiles()
    //   this.form.fileUpload = file[0]
    // },
    handleChange(file, fileList, row) {
      const _file = file?.raw ?? file
      const formData = new FormData()
      formData.append('file', _file)
      formData.append('pathType', file.name.split('.').pop())
      uploadFile(formData).then(res => {
        row.fileName = res.data.fileName
        row.fileOriginPath = res.data.filePath
        row.filePath = res.data.servicePath
      })
    },
    // 多次上传覆盖
    handleExceed(file, row) {
      this.$refs.uploadRef.clearFiles()
      this.handleChange(file[0], '', row)
    },

    deleteFun(row) {
      let itemIndex = this.tableData.findIndex(function (obj) {
        return row === obj
      })
      this.tableData.splice(itemIndex, 1)
    },
    delFile(row) {
      let itemIndex = this.tableDataFile.findIndex(function (obj) {
        return row === obj
      })
      if (row.fileOriginPath) {
        deleteFile({ files: [row.fileOriginPath] }).then(() => {
          this.tableDataFile.splice(itemIndex, 1)
        })
      } else {
        this.tableDataFile.splice(itemIndex, 1)
      }
    }
  }
}
</script>

<style lang="less" scoped>
  ::v-deep.flex-rowform {
    .el-form-item__content {
      display: flex;
    }
    .r-span {
      display: inline-block;
      width: 100px;
      line-height: 40px;
    }
  }
  .person {
    position: relative;
    .r-btn {
      position: absolute;
      top: 16px;
      right: 0;
    }
  }
  .upload-demo {
    display: inline-block;
    padding-right: 10px;
  }
  .header {
    position: relative;
    .saveBtn {
      position: absolute;
      right: 20px;
      top: 10px;
    }
  }
</style>